﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Eagles.Application.Model;
using Eagles.Application.Model.ActivityTask.Model;
using Eagles.Application.Model.Common;
using Eagles.Application.Model.News.Model;
using Eagles.Application.Model.News.Requset;
using Eagles.Application.Model.PartyMember.Requset;
using Eagles.Application.Model.Publicity.Model;
using Eagles.Application.Model.Publicity.Request;
using Eagles.Application.Model.Publicity.Response;
using Eagles.Base;
using Eagles.Base.Cache;
using Eagles.DomainService.Model.Activity;
using Eagles.DomainService.Model.News;
using Eagles.DomainService.Model.Oper;
using Eagles.DomainService.Model.User;
using Eagles.Interface.Core;
using Eagles.Interface.DataAccess;
using Step = Eagles.Application.Model.ActivityTask.Model.Step;

namespace Eagles.DomainService.Core
{
    public class PublicityHandler: IPublicityHandler
    {
        private readonly IPublicityDataAccess dataAccess;

        private readonly IPartyMemberDataAccess UserdataAccess;

        private readonly INewsDataAccess NewdataAccess;

        private readonly ICacheHelper cacheHelper;

        private readonly IOperDataAccess OperdataAccess;

        public PublicityHandler(ICacheHelper cacheHelper, IPublicityDataAccess dataAccess, IPartyMemberDataAccess userdataAccess, INewsDataAccess newdataAccess, IOperDataAccess operdataAccess)
        {
            this.cacheHelper = cacheHelper;
            this.dataAccess = dataAccess;
            UserdataAccess = userdataAccess;
            NewdataAccess = newdataAccess;
            OperdataAccess = operdataAccess;
        }

        public GetPublicActivityDetailResponse GetPublicActivityDetail(GetPublicActivityDetailRequest requset)
        {

            var response = new GetPublicActivityDetailResponse
            {

            };
            TbActivity detail = dataAccess.GetPublicActivityDetail(requset);

            if (detail == null) throw new TransactionException("M01");

            int count = dataAccess.GetActivityUserCount(requset.ActivityId);

            //var createType = detail.CreateType;
            //var userId = 0;
            ////上级发起的活动
            //if (0 == createType)
            //    userId = detail.ToUserId;
            ////下级发起的活动
            //else if (1 == createType)
            //    userId = detail.FromUser;
            var result = dataAccess.GetActivityFeedBack(requset.ActivityId,detail.OrgId, detail.ToUserId);

            var attac = new List<Attachment>()
            {
                new Attachment()
                {
                    AttachmentUrl = detail.Attach1,
                    AttachmentName = detail.AttachName1
                },
                new Attachment()
                {
                    AttachmentUrl = detail.Attach2,
                    AttachmentName = detail.AttachName2
                },
                new Attachment()
                {
                    AttachmentUrl = detail.Attach3,
                    AttachmentName = detail.AttachName3
                },new Attachment()
                {
                    AttachmentUrl = detail.Attach4,
                    AttachmentName = detail.AttachName4
                },
            };
            response.Info = new PublicActivitydetail
            {
                ActivityId = detail.ActivityId,
                ActivityName = detail.ActivityName,
                ActivityDesc=detail.HtmlContent,
                ResponsibleUserName =
                UserdataAccess.GetUserInfoDetail(new GetUserInfoDetailRequest {UserId = detail.ToUserId})?.Name,
                UserCount = count,
                CreateTime=detail.CreateTime,
                AduitUserName= UserdataAccess.GetUserInfoDetail(new GetUserInfoDetailRequest { UserId = detail.AuditUserId })?.Name,
                ActivityContent= detail.HtmlContent,
                Attachments= attac.Where(x => !string.IsNullOrWhiteSpace(x.AttachmentName) || !string.IsNullOrWhiteSpace(x.AttachmentUrl)).ToList(),
                FeedBackList=  new FeedBack
                {
                    UserId = result.UserId,
                    UserName = result.Name,
                    UserFeedBack = result.UserFeedBack,
                    FeedBackTime = result.FeedBackTime.ToString("yyyy-MM-dd"),
                    AttachList = new List<Attachment>()
                    {
                        new Attachment() { AttachmentName = result.AttachName1, AttachmentUrl = result.Attach1 },
                        new Attachment() { AttachmentName = result.AttachName2, AttachmentUrl = result.Attach2 },
                        new Attachment() { AttachmentName = result.AttachName3, AttachmentUrl = result.Attach3 },
                        new Attachment() { AttachmentName = result.AttachName4, AttachmentUrl = result.Attach4 }
                    }.Where(ff => !string.IsNullOrWhiteSpace(ff.AttachmentName) || !string.IsNullOrWhiteSpace(ff.AttachmentUrl)).ToList()
                }
        };

         




            return response;

        }

        public GetPublicActivityResponse GetPublicActivity(RequestBase requset,int type)
        {

            var token = cacheHelper.GetData<TbUserToken>(requset.Token);

            var userinfo = OperdataAccess.GetOperDetail(token.UserId)?? new TbOper();

            type = userinfo.BranchId > 0 ? 2 : 1;

            var response = new GetPublicActivityResponse
            {
                TotalCount = 0,
            };
            List<TbActivity> list = dataAccess.GetPublicActivity(requset, type, userinfo.BranchId, out int i) ?? new List<TbActivity>();

            List<ActivityUserCount> count = dataAccess.GetActivityUserCount();

            if (list.Count == 0) throw new TransactionException("M01");

            var userInfo = UserdataAccess.GetUserInfoList(list.Select(x => x.AuditUserId).ToList()
                .Union(list.Select(x => x.ToUserId).ToList()).ToList());

            response.TotalCount = i;
            response.Activitys = list.Select(x => new PublicActivity
            {
                ActivityId = x.ActivityId,
                ActivityName = x.ActivityName,
                ResponsibleUserName = userInfo.FirstOrDefault(f => f.UserId == x.ToUserId)?.Name,
                AduitUserName = userInfo.FirstOrDefault(f => f.UserId == x.AuditUserId)?.Name,
                CreateTime = x.CreateTime,
                UserCount = count.Any(d => d.ActivityId == x.ActivityId)
                    ? count.First(d => d.ActivityId == x.ActivityId).Count
                    : 0,
                Status= -1

            }).ToList();
            return response;
        }

        public GetPublicTaskDetailResponse GetPublicTaskDetail(GetPublicTaskDetailRequest requset)
        {
            var response = new GetPublicTaskDetailResponse
            {

            };
            TbTask detail = dataAccess.GetPublicTaskDetail(requset);

            if (detail == null) throw new TransactionException("M01");

            List<TbUserTaskStep> result = dataAccess.GetTaskStep(requset.TaskId);

            response.info = new PublicTaskDetail()
            {
                //FromUser=detail.FromUser,
                TaskTitle = detail.TaskName,
                TaskId = detail.TaskId,
                TaskContent = detail.TaskContent,
                CreateTime = detail.CreateTime,
               
                Attachments = new List<Attachment>()
                {
                    new Attachment()
                    {
                        AttachmentName = detail.AttachName2,
                        AttachmentUrl = detail.Attach2
                    },
                    new Attachment()
                    {
                        AttachmentName = detail.AttachName3,
                        AttachmentUrl = detail.Attach3
                    },
                    new Attachment()
                    {
                        AttachmentName = detail.AttachName1,
                        AttachmentUrl = detail.Attach1
                    },
                    new Attachment()
                    {
                        AttachmentName = detail.AttachName4,
                        AttachmentUrl = detail.Attach4
                    }
                },
                ResponsibleUserName =
                    UserdataAccess.GetUserInfoDetail(new GetUserInfoDetailRequest { UserId = detail.FromUser })?.Name,
                AduitUserName = 
                    UserdataAccess.GetUserInfoDetail(new GetUserInfoDetailRequest { UserId = detail.AuditUserId })?.Name,
                Steps = result?.Select(x => new Step
                {
                    StepId = x.StepId,
                    StepName = x.StepName,
                    StepContent = x.Content,

                }).ToList()


                // UserCount=detail
            };


            response.info.Attachments = response.info.Attachments
                .Where(x => !string.IsNullOrWhiteSpace(x.AttachmentName) || !string.IsNullOrWhiteSpace(x.AttachmentUrl)).ToList();
            return response;

        }

        public GetPublicTaskResponse GetPublicTask(RequestBase requset, int type)
        {

            var token = cacheHelper.GetData<TbUserToken>(requset.Token);

            var userinfo = OperdataAccess.GetOperDetail(token.UserId) ?? new TbOper();


            type = userinfo.BranchId > 0 ? 2 : 1;

            var response = new GetPublicTaskResponse
            {
                TotalCount = 0,
            };
            List<TbTask> list = dataAccess.GetPublicTask(requset, type, userinfo.BranchId, out int i) ?? new List<TbTask>();

            var userInfo = UserdataAccess.GetUserInfoList(list.Select(x => x.AuditUserId).ToList()
                .Union(list.Select(x => x.FromUser).ToList()).ToList());

            if (list.Count == 0) throw new TransactionException("M01");
            response.TotalCount = i;
            response.Tasks = list.Select(x => new PublicTask
            {
                CreateTime = x.CreateTime,
                // ResponsibleUserName=x.us
                TaskId = x.TaskId,
                TaskTitle = x.TaskName,
               // ResponsibleUserName = x.FromUserName,
                Status= -1,
                ResponsibleUserName = userInfo.FirstOrDefault(f => f.UserId == x.FromUser)?.Name,
                AduitUserName = userInfo.FirstOrDefault(f => f.UserId == x.AuditUserId)?.Name,
            }).ToList();
            return response;
        }

        public GetAritcleDetailResponse GetAritcleDetail(GetPublicArticleDetailRequest requset)
        {

            var response = new GetAritcleDetailResponse
            {
                //  CreateTime = x.CreateTime,
                // ResponsibleUserName=x.us


            };

            TbUserNews detail = dataAccess.GetNewsDetail(requset.NewsId);

           var userinfo =  UserdataAccess.GetUserInfoDetail(new GetUserInfoDetailRequest()
            {
                UserId = detail.UserId
            });

            response.info = new AritcleDetail
            {
                Name = userinfo?.Name,
                CreateTime = detail.CreateTime,
                NewsId = detail.NewsId,
                NewsDetail = detail.HtmlContent,
                NewsTitle = detail.Title,
                NewsType=detail.NewsType,
                
                
                // Category=detail.ViewCount
            };
            return response;
        }

        public GetPublicAritcleResponse GetPublicArticle(RequestBase requset, int type)
        {

         
            var response = new GetPublicAritcleResponse
            {

            };
            var token = cacheHelper.GetData<TbUserToken>(requset.Token);

            var userinfo = OperdataAccess.GetOperDetail(token.UserId) ?? new TbOper();

            type = userinfo.BranchId > 0 ? 2 : 1;

         



            List<TbUserNews> list = NewdataAccess.GetNewsList(requset.Token, type, userinfo.BranchId, out int totalCount) ??
                                    new List<TbUserNews>();

            if (list.Count == 0) throw new TransactionException("M01");

            var userlist = UserdataAccess.GetUserInfoList(list.Select(x => x.UserId).ToList());
            response.TotalCount = totalCount;

            response.Aritcles = list.Select(x => new Aritcle
            {
                CreateTime = x.CreateTime,
                NewsId = x.NewsId,
                // NewsType = x.NewsType,
                NewsTitle = x.Title,
                NewsType = x.NewsType,
                Name = userlist.FirstOrDefault(w => w.UserId == x.UserId)?.Name,
                Status=-1
            }).ToList();
            return response;

        }
    }
}
